<template>
  <div class="p-2">
    <!--    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">-->
    <!--      <div v-show="showSearch" class="mb-[10px]">-->
    <!--        <el-card shadow="hover">-->
    <!--          <el-form ref="queryFormRef" :model="queryParams" :inline="true">-->
    <!--            <el-form-item>-->
    <!--              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>-->
    <!--              <el-button icon="Refresh" @click="resetQuery">重置</el-button>-->
    <!--            </el-form-item>-->
    <!--          </el-form>-->
    <!--        </el-card>-->
    <!--      </div>-->
    <!--    </transition>-->

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <!--          <el-col :span="1.5">-->
          <!--            <el-button v-hasPermi="['system:registration:add']" type="primary" plain icon="Plus" @click="handleAdd"> 新增 </el-button>-->
          <!--          </el-col>-->
          <!--          <el-col :span="1.5">-->
          <!--            <el-button v-hasPermi="['system:registration:edit']" type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"-->
          <!--              >修改-->
          <!--            </el-button>-->
          <!--          </el-col>-->
          <!--          <el-col :span="1.5">-->
          <!--            <el-button v-hasPermi="['system:registration:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"-->
          <!--              >删除-->
          <!--            </el-button>-->
          <!--          </el-col>-->
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:registration:export']" type="warning" plain icon="Download" @click="handleExport">导出 </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="registrationList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column v-if="true" label="ID" align="center" prop="id" />
        <el-table-column label="会员名" align="center" prop="memberName" />
        <el-table-column label="就诊人" align="center" prop="patientName" />
        <el-table-column label="医生备注" align="center" prop="remark" width="120" show-overflow-tooltip />
        <el-table-column label="所属医生" align="center" prop="doctorName" />
        <el-table-column label="所属科室" align="center" prop="title" width="120" show-overflow-tooltip />
        <el-table-column label="身份证号" align="center" prop="idCard" width="140" show-overflow-tooltip />
        <el-table-column label="手机号" align="center" prop="mobile" width="120" />
        <el-table-column label="就诊日期" align="center" prop="registrationTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.registrationTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="总金额" align="center" prop="totalPrice" />
        <el-table-column label="支付金额" align="center" prop="payPrice" />
        <el-table-column label="支付时间" align="center" prop="payTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.payTime, '{y}-{m}-{d}  {hh}:{mm}:{ss}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status" width="120">
          <template #default="scope">
            <dict-tag :options="registration_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width" width="180">
          <template #default="scope">
            <el-tooltip v-if="scope.row.status == 200" content="已就诊" placement="top">
              <el-button
                v-hasPermi="['system:registration:seeAdoctor']"
                link
                type="primary"
                icon="FolderChecked"
                @click="handleUpdate(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="备注" placement="top">
              <el-button v-hasPermi="['system:registration:remark']" link type="primary" icon="EditPen" @click="handleRemark(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip v-if="scope.row.status == 200 || scope.row.status == 400" content="申请退款" placement="top">
              <el-button v-hasPermi="['system:memberRefund:audit']" link type="primary" icon="Setting" @click="handleRefund(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['system:registration:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
    <!-- 备注对话框 -->
    <el-dialog v-model="remarkDialog.visible" :title="remarkDialog.title" width="500px" append-to-body>
      <el-form ref="registrationFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="remarkSubmitForm">确 定</el-button>
          <el-button @click="remarkDialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 退款对话框 -->
    <el-dialog v-model="refundDialog.visible" :title="refundDialog.title" width="500px" append-to-body>
      <el-form ref="refundFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="退款原因" prop="cause">
          <el-input v-model="form.cause" type="textarea" placeholder="请输入退款原因" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="退款状态" clearable>
            <el-option v-for="dict in refundStatusOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="refundSubmitForm">确 定</el-button>
          <el-button @click="refundDialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 添加或修改挂号记录对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="500px" append-to-body>
      <el-form ref="registrationFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="会员id" prop="memberId">
          <el-input v-model="form.memberId" placeholder="请输入会员id" />
        </el-form-item>
        <el-form-item label="就诊卡id" prop="patientId">
          <el-input v-model="form.patientId" placeholder="请输入就诊卡id" />
        </el-form-item>
        <el-form-item label="就诊日期" prop="registrationTime">
          <el-date-picker v-model="form.registrationTime" clearable type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择就诊日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="总金额" prop="totalPrice">
          <el-input v-model="form.totalPrice" placeholder="请输入总金额" />
        </el-form-item>
        <el-form-item label="支付金额" prop="payPrice">
          <el-input v-model="form.payPrice" placeholder="请输入支付金额" />
        </el-form-item>
        <el-form-item label="支付时间" prop="payTime">
          <el-date-picker v-model="form.payTime" clearable type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择支付时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Registration" lang="ts">
import { listRegistration, delRegistration, addRegistration, updateRegistration } from '@/api/system/registration';
import { RegistrationVO, RegistrationQuery, RegistrationForm } from '@/api/system/registration/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { registration_status } = toRefs<any>(proxy?.useDict('registration_status'));
const registrationList = ref<RegistrationVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const refundStatusOptions = [{ label: '同意退款', value: 1 }];

const queryFormRef = ref<ElFormInstance>();
const registrationFormRef = ref<ElFormInstance>();
const refundFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const remarkDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const refundDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: RegistrationForm = {
  id: undefined,
  memberId: undefined,
  patientId: undefined,
  registrationTime: undefined,
  totalPrice: undefined,
  payPrice: undefined,
  payTime: undefined,
  status: undefined,
  remark: undefined,
  cause: undefined,
  checkStatus: undefined
};
const data = reactive<PageData<RegistrationForm, RegistrationQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    memberId: undefined,
    patientId: undefined,
    registrationTime: undefined,
    totalPrice: undefined,
    payPrice: undefined,
    payTime: undefined,
    status: undefined,
    remark: undefined,
    cause: undefined,
    checkStatus: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '主键id不能为空', trigger: 'blur' }],
    memberId: [{ required: true, message: '会员id不能为空', trigger: 'blur' }],
    patientId: [{ required: true, message: '就诊卡id不能为空', trigger: 'blur' }],
    registrationTime: [{ required: true, message: '就诊日期不能为空', trigger: 'blur' }],
    totalPrice: [{ required: true, message: '总金额不能为空', trigger: 'blur' }],
    payPrice: [{ required: true, message: '支付金额不能为空', trigger: 'blur' }],
    payTime: [{ required: true, message: '支付时间不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '状态不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询挂号记录列表 */
const getList = async () => {
  loading.value = true;
  const res = await listRegistration(queryParams.value);
  registrationList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  registrationFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: RegistrationVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加挂号记录';
};

/** 已就诊按钮操作 */
const handleUpdate = async (row?: RegistrationVO) => {
  console.log(row, 'row');
  await proxy?.$modal.confirm('确认挂号记录编号为"' + row.id + '"的数据项已就诊？').finally(() => (loading.value = false));
  await updateRegistration({
    id: row.id,
    status: 400
  });
  proxy?.$modal.msgSuccess('操作成功');
  await getList();
};

/** 备注按钮操作 */
const handleRemark = async (row?: RegistrationVO) => {
  reset();
  form.value.id = row.id;
  form.value.remark = row.remark;
  remarkDialog.visible = true;
  remarkDialog.title = '挂号记录备注';
};

/** 备注提交按钮 */
const remarkSubmitForm = async () => {
  await updateRegistration({
    id: form.value.id,
    remark: form.value.remark
  }).finally(() => (buttonLoading.value = false));
  proxy?.$modal.msgSuccess('操作成功');
  remarkDialog.visible = false;
  await getList();
};

/** 退款按钮操作 */
const handleRefund = async (row?: RegistrationVO) => {
  reset();
  form.value.id = row.id;
  form.value.remark = row.remark;
  refundDialog.visible = true;
  refundDialog.title = '挂号记录退款';
};

/** 退款提交按钮 */
const refundSubmitForm = async () => {
  refundFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      await updateRegistration({
        id: form.value.id,
        status: form.value.status,
        cause: form.value.cause
      }).finally(() => (buttonLoading.value = false));
      proxy?.$modal.msgSuccess('操作成功');
      refundDialog.visible = false;
      await getList();
    }
  });
};

/** 提交按钮 */
const submitForm = () => {
  registrationFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateRegistration(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addRegistration(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: RegistrationVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除挂号记录编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delRegistration(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'system/registration/export',
    {
      ...queryParams.value
    },
    `registration_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
});
</script>
